package edu.ustb.efws.pipeline.collect.handler;

import edu.ustb.efws.pipeline.collect.handler.meter.MeterPointPool;
import edu.ustb.efws.pipeline.domain.RiskLog;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 测量点处理
 *
 * @author TS Group
 */
class MeterPointHandler implements PipelineHandler {
    private final MeterPointPool pool;

    /**
     * {@link MeterPointHandler}
     *
     * @param pool {@link MeterPointPool}
     */
    MeterPointHandler(MeterPointPool pool){
        this.pool = pool;
    }

    @Override
    @SuppressWarnings("unchecked")
    public Optional<Object> handle0(Object data) {
        List<RiskLog> logs = (List<RiskLog>) data;
        if(logs.isEmpty()){
            return Optional.of(logs);
        }

        if(isThosPosition(logs)){
            buildThosPositionMeter(logs).forEach(pool::push);
        }else{
            logs.forEach(pool::push);
        }

        return Optional.of(data);
    }

    private boolean isThosPosition(List<RiskLog> logs){
        int positionId = logs.get(0).getPositionId();
        return positionId >= 50 && positionId <= 58;
    }

    private List<RiskLog> buildThosPositionMeter(List<RiskLog> logs){
        int pId = logs.get(0).getPositionId();
        int positionId = pId >= 50 && pId <= 52? 50 : 53;

        return logs.stream().flatMap(e ->
                Stream.of(buildLog(positionId, e.getT(), e), buildLog(positionId * 10, e.getH(), e)))
                .collect(Collectors.toList());
    }

    private RiskLog buildLog(int positionId, float score, RiskLog t){
        RiskLog log = new RiskLog();
        log.setPositionId(positionId);
        log.setMonth(t.getMonth());
        log.setIptTime(t.getIptTime());
        log.setThosTime(t.getThosTime());
        log.setScore(score);

        return log;
    }
}
